package com.nbcb.fund.common.config;

import com.nbcb.fund.common.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 九分石人
 */
@Configuration
public class WebConfigure implements WebMvcConfigurer {

    @Resource
    LoginInterceptor loginInterceptor;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> pathPattern = new ArrayList<>();
        pathPattern.add("/**");
        List<String> excludePattern = new ArrayList<>();
        excludePattern.add("/user/login");
        excludePattern.add("/user/register");
        excludePattern.add("/swagger-ui/**");
        excludePattern.add("/swagger-resources/**");
        excludePattern.add("/webjars/**");
        excludePattern.add("/v2/**");
        excludePattern.add("/swagger-ui.html/**");
        excludePattern.add("/v3/api-docs");
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns(pathPattern)
                .excludePathPatterns(excludePattern);
    }

//    @Override
//    public void addCorsMappings(CorsRegistry registry){
//        registry.addMapping("/**")
//                .allowedOrigins("*")
//                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
//                .allowCredentials(true)
//                .maxAge(3600)
//                .allowedHeaders("*");
//    }

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.setAllowCredentials(true);
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.addExposedHeader("*");
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        return new CorsFilter(configSource);
    }


}
